package com.project.baseTest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {
    public CustomRealm() {
        //创建凭证匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密算法
        matcher.setHashAlgorithmName("md5");
        //设置散列次数
        matcher.setHashIterations(1024);
        //如果设置加密编码为true表示hex编码，为false用Base64编码
        matcher.setStoredCredentialsHexEncoded(true);
        //将realm设置凭证管理器
        this.setCredentialsMatcher(matcher);
    }
    /**
     * 用于授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到主题名称、也就是用户名
        String username = principalCollection.getPrimaryPrincipal().toString();

        if ("tom".equals(username)) {
            //创建一个授权的对象
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            //给用户授予角色集合，授权后，该用户拥有这些角色对应的权限
            authorizationInfo.addRoles(List.of("custom","manager","order"));
            //给用户授予指定权限
            authorizationInfo.addStringPermission("user:create");
            authorizationInfo.addStringPermission("order:*");

            return authorizationInfo;
        }
        return null;
    }

    /**
     * 用于认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //得到登录主体用户名
        String userName =authenticationToken.getPrincipal().toString();
        if ("tom".equals(userName)){
            //返回认证对象，第一个参数为主体，第二个参数为密码，第三个参数为realm名称
            return new SimpleAuthenticationInfo(userName,"943157a350ea16c8443016ae7100211c",
                    ByteSource.Util.bytes("pxw".getBytes()),this.getName());
        }
        return null;
    }
}
